package app.server.project.cloud.random.service;

import app.server.project.cloud.random.dto.device.GenUUidReq;
import app.server.project.core.constants.CfgDef;
import app.server.project.core.constants.Def;
import app.server.project.core.exception.SysError;
import app.server.project.core.util.AssertUtil;
import app.server.project.cloud.random.db.entity.DeviceBaseEntity;
import app.server.project.cloud.random.dto.device.GenDevResp;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

@Service
public class DeviceBaseService {

    @Value("${" + "spring.web.resources.static-locations" + "}")
    private String filePath;
    @Autowired
    private TaskScheduler taskScheduler;
    /**
     * 生成id
     * @param model
     * @return
     */
    public GenDevResp genDeviceId(GenUUidReq model){
        AssertUtil.isTrue(model.getNum()> Def.Zero, SysError.Sys);
        String csvFile="/csv/";
        String retPath=filePath+csvFile;
        String uuid=IdUtil.fastSimpleUUID();
        String finalPath=retPath+uuid;
        var csvW= CsvUtil.getWriter(finalPath, CharsetUtil.CHARSET_UTF_8);
        List<String[]> ids=new ArrayList<>();
        List<DeviceBaseEntity> list=new ArrayList<>();
        for (int i = 0; i < model.getNum(); i++) {
            var id=IdUtil.getSnowflakeNextId();
            ids.add(new String[] {String.valueOf(id)});
            list.add(DeviceBaseEntity.of(id, model.getDeviceTypeId()));
        }
        csvW.write(ids);
        csvW.close();
        this.taskScheduler.schedule(()->{
            FileUtil.del(finalPath);
        }, Instant.now().plusSeconds(10*1));
        return GenDevResp.of("/static"+csvFile+uuid,uuid);
    }
}
